package com.carey.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.carey.yygh.hosp.repository.DepartmentRepository;
import com.carey.yygh.hosp.service.DepartmentService;
import com.carey.yygh.model.hosp.Department;
import com.carey.yygh.vo.hosp.DepartmentQueryVo;
import com.carey.yygh.vo.hosp.DepartmentVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentRepository departmentRepository;

    @Override
    public void saveDepartment(Map<String, Object> switchMap) {
        Department department = JSONObject.parseObject(JSONObject.toJSONString(switchMap), Department.class);
        //判断是否存在
        Department departmentExist = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        if (null!= departmentExist){
            //存在 修改
            department.setId(departmentExist.getId());
            department.setIsDeleted(0);
            department.setUpdateTime(new Date());
            department.setCreateTime(departmentExist.getCreateTime());
            departmentRepository.save(department);
        }else {
            //不存在 就添加
            department.setCreateTime(new Date());
            department.setIsDeleted(0);
            department.setUpdateTime(new Date());
            departmentRepository.save(department);
        }
    }

    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page-1,limit,sort);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo,department);
        department.setIsDeleted(0);

        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        //创建实例
        Example<Department> example = Example.of(department, matcher);

        Page<Department> pages = departmentRepository.findAll(example, pageable);
        return pages;
    }

    @Override
    public void removeDepartment(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if (null != department){
            departmentRepository.deleteById(department.getId());
        }
    }

    /**
     * 想得到这种结构的json数据返回给前端
     *
     * {
     *       "depcode": "a4e171f4cf9b6816acdfb9ae62c414d7",  （big）
     *       "depname": "专科",
     *       "children": [
     *         {
     *           "depcode": "200040878",
     *           "depname": "多发性硬化专科门诊",
     *           "children": null
     *         },
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> getDepLIst(String hoscode) {
        List<DepartmentVo> result = new ArrayList<>();
        //先查询所有科室信息
        Department department = new Department();
        department.setHoscode(hoscode);
        Example<Department> example = Example.of(department);
        List<Department> departmentList = departmentRepository.findAll(example);
        //stream流分组
        Map<String, List<Department>> map = departmentList.stream()
                .collect(Collectors.groupingBy(Department::getBigcode));
        //循环遍历
        map.entrySet().forEach(item ->{
            //得到big的code和name
            String bigcode = item.getKey();
            List<Department> list = item.getValue();
            String bigname = list.get(0).getBigname();
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(bigcode);
            departmentVo.setDepname(bigname);
            //设置big中的childern
            List<DepartmentVo> children = new ArrayList<>();//children是list集合
            list.forEach(department1 -> { //遍历分组得到的list
                DepartmentVo departmentVo1 = new DepartmentVo();
                departmentVo1.setDepname(department1.getDepname());
                departmentVo1.setDepcode(department1.getDepcode());
                children.add(departmentVo1);
            });
            departmentVo.setChildren(children);//给big中的chileren赋值
            result.add(departmentVo);
        });
        return result;
    }

    //根据科室编号，和医院编号，查询科室名称
    @Override
    public String getDepName(String hoscode, String depcode) {
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(department != null) {
            return department.getDepname();
        }
        return null;
    }

    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }


}
